package eai.tp2.lpco.web.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import eai.tp2.lpco.credentials.register.IRegistry;
import eai.tp2.lpco.database.User;
import eai.tp2.lpco.web.beans.ErrorList;
import eai.tp2.lpco.web.beans.UserBean;

/**
 * Servlet implementation class Register
 */
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Register() {
        super();
        // TODO Auto-generated constructor stub
    }	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		IRegistry registry= null;
		InitialContext ctx = null;
		try {
			ctx = new InitialContext();
			registry = (IRegistry) ctx.lookup("RegisterBean/remote");			
		} catch (NamingException e) {			
			e.printStackTrace();
		}
		User user = new User();
		user.setUsername(request.getParameter("username"));
		user.setFullName(request.getParameter("name"));
		user.setAddress(request.getParameter("address"));
		user.setEmail(request.getParameter("e_mail"));
		user.setPassword(request.getParameter("password"));
		if(registry.saveUserInfo(user)) {
			UserBean usr = new UserBean();
			usr.setUsername(user.getUsername());
			session.setAttribute("user", usr);
			response.sendRedirect("list.jsp");
		}else {
			String error;
			error = "The user already exists. Try again.";
			List<String> errors = new ArrayList<String>();
			errors.add(error);
			ErrorList list = new ErrorList();
			list.setErrorList(errors);		
			request.setAttribute("list", list);
			RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
			rd.forward(request, response);	
		}
	}

}
